#!/bin/bash

MYSQL_PATH=/usr/local/mysql

MYSQL_DATA=$MYSQL_PATH/data

MYSQL_LOG=$MYSQL_PATH/logs

MYSQL_PASSWD="root123"

banben=mysql-8.0.20-linux-glibc2.12-x86_64.tar.xz

set -euo pipefail


# sudo bash -c 'echo "nameserver 8.8.8.8" > /etc/resolv.conf'
# sudo bash -c 'echo "nameserver 1.1.1.1" >> /etc/resolv.conf'

function yilai(){

which apt &> /dev/null

if [[ $? -eq 0 ]];then

echo '是ubuntu系统'
sudo apt update
sudo apt install -y libaio1 libaio-dev libtinfo5 libncurses-dev libncurses5 libncurses5-dev libncursesw5 libncursesw5-dev libssl-dev
sudo apt update && sudo apt install -y expect
echo '已经安装依赖'

else

echo '是centos系统'
sudo yum install -y libaio libaio-devel ncurses ncurses-devel openssl openssl-devel
sudo yum install -y expect
echo '已安装依赖'


fi
}

#yilai


function xiazai(){

cd /usr/local/

wget https://downloads.mysql.com/archives/get/p/23/file/$banben


 if [[ -f $banben ]];then

tar -xvf mysql-8.0.20-linux-glibc2.12-x86_64.tar.xz -C /usr/local/

mv mysql-8.0.20-linux-glibc2.12-x86_64 mysql
echo '解压成功'

else

echo '安装失败'


fi

}
# xiazai




function yonghu(){
    if id mysql &>/dev/null; then
        echo "mysql 用户已存在，跳过创建"
    else
        useradd -r -M -s /sbin/nologin mysql
        echo "已创建 mysql 系统用户"
    fi
}


#yonghu





function peizhi(){
    local cnf=/etc/my.cnf
    # 如果已存在则备份
    [[ -f $cnf ]] && { log_warn "$cnf 已存在，备份为 $cnf.bak"; cp $cnf $cnf.bak; }

   echo "生成 $cnf"
    cat << 'EOF' > $cnf
[mysqld]
port = 3306
basedir = /usr/local/mysql
datadir = /usr/local/mysql/data
log-error = /usr/local/mysql/data/error.log
pid-file = /usr/local/mysql/data/mysql.pid
socket = /tmp/mysql.sock
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
default-storage-engine = InnoDB
default-authentication-plugin = mysql_native_password
sql_mode = NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

[client]
socket = /tmp/mysql.sock
default-character-set = utf8mb4
EOF
    echo "$cnf 已写入"
}

#peizhi




function chushihua(){
    local basedir=/usr/local/mysql
    local datadir=$basedir/data
    local errlog=$datadir/error.log

    echo "正在确保 data 目录为空并重新赋权"
    pkill -f mysqld || true

    # 1. 用 root 整个目录掀掉再建
    sudo rm -rf "$datadir"
    sudo mkdir -p "$datadir"

    # 2. 一次性赋权
    sudo chown -R mysql:mysql "$basedir"
    sudo chmod 750 "$datadir"

    echo "开始初始化数据目录"
    # 3. 初始化
    sudo -u mysql "$basedir/bin/mysqld" --initialize \
        --user=mysql \
        --basedir="$basedir" \
        --datadir="$datadir" \
        2>"$errlog"

    # 4. 取临时密码
    TEMP_PWD=$(awk '/temporary password/{print $NF}' "$errlog")
    if [[ -z $TEMP_PWD ]]; then
        echo "未找到临时密码，请检查 $errlog 末尾 50 行"
        tail -n 50 "$errlog"
        exit 1
    fi

    echo "初始化完成，临时密码：$TEMP_PWD"
    export TEMP_PWD




    # 1. 停掉残留
sudo pkill -f mysqld || true

# 2. 整个 data 目录掀掉重建
sudo rm -rf /usr/local/mysql/data
sudo mkdir /usr/local/mysql/data
sudo chown -R mysql:mysql /usr/local/mysql

# 3. 再初始化
sudo -u mysql /usr/local/mysql/bin/mysqld --initialize \
  --user=mysql \
  --basedir=/usr/local/mysql \
  --datadir=/usr/local/mysql/data

}

#chushihua








function gaimima(){
    local new_pwd="091600"                                
    local basedir=/usr/local/mysql
    local mysql="$basedir/bin/mysql"
    local sock=/tmp/mysql.sock
    local errlog=$basedir/data/error.log

    # 1. 取临时密码（初始化后已生成）
    TEMP_PWD=$(awk '/temporary password/{print $NF}' "$errlog")
    if [[ -z $TEMP_PWD ]]; then
        echo "未找到临时密码，无法继续"
        exit 1
    fi

    # 2. 如果实例没启动，先启动
    if [[ ! -S $sock ]]; then
        echo "启动 mysqld ..."
        sudo -u mysql "$basedir/bin/mysqld" --defaults-file=/etc/my.cnf --daemonize
        sleep 3
    fi

    # 3. expect 自动应答
    expect <<EOF
set timeout 10
spawn $mysql -uroot -p --socket=$sock
expect "Enter password:" { send "$TEMP_PWD\r" }
expect "mysql>" {
    send "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$new_pwd';\r"
}
expect "mysql>" {
    send "DELETE FROM mysql.user WHERE User='';\r"
}
expect "mysql>" {
    send "DROP DATABASE IF EXISTS test;\r"
}
expect "mysql>" {
    send "FLUSH PRIVILEGES;\r"
}
expect "mysql>" { send "exit\r" }
expect eof
EOF

    if [[ $? -eq 0 ]]; then
        echo "root 密码已修改为：$new_pwd"
    else
        echo "改密失败"; exit 1
    fi
}



#gaimima



# function bianliang(){
#     local basedir=/usr/local/mysql
#     local profile=/etc/profile.d/mysql.sh

#     echo "export PATH=\$PATH:$basedir/bin" | sudo tee "$profile" >/dev/null
#     sudo chmod 644 "$profile"

#     # 当前 shell 立即生效
#     source "$profile"

#     echo "MySQL 环境变量已写入 $profile"
#     echo "当前 PATH：$PATH"


    
# }

function bianliang(){
   echo 'export PATH=$PATH:/usr/local/mysql/bin' | sudo tee /etc/profile.d/mysql.sh
sudo chmod 644 /etc/profile.d/mysql.sh

source /etc/profile.d/mysql.sh

}

    
bianliang
  




